﻿///////////////////////////////////////////////////////////////////////////////
// File:        Socket.cc
// Author:      671643387@qq.com
// Description:
///////////////////////////////////////////////////////////////////////////////

#include "nio/net/Socket.hpp"
using namespace nio::net;

Socket::Socket(void)
    : sock_(INVALID_SOCKET)
{

}

Socket::Socket(int family, int type, int protocol /* = 0 */)
    : sock_(Socket::create(family, type, protocol))
{
    assert(sock_ != INVALID_SOCKET);
}

Socket::Socket(sock_t sock)
    : sock_(sock)
{

}

Socket::~Socket()
{
    close();
}

int Socket::read(sock_t sock, char* buff, unsigned int length, int flags)
{
#if defined(__WINDOWS__)
    int ret = ::recv(sock, buff, int(length), flags);
#elif defined(__LINUX__)
    int ret = ::recv(sock, buff, length, flags);
#endif
    if (ret == SOCKET_ERROR)
    {
#if defined(__LINUX__)
        if (errno == EWOULDBLOCK)
        {
            return SOCKET_ERROR_WOULDBLOCK;
        }
#elif defined(__WINDOWS__)
        int wsaError = WSAGetLastError();
        if (wsaError == WSAEWOULDBLOCK)
        {
            return SOCKET_ERROR_WOULDBLOCK;
        }
#endif
    }
    else if (ret == 0)
    {
    }
    return ret;
}

int Socket::write(sock_t sock, const char* buff, unsigned int length, int flags)
{
#if defined(__WINDOWS__)
    int ret = ::send(sock, buff, int(length), flags);
#elif defined(__LINUX__)
    int ret = ::send(sock, buff, length, flags);
#endif
    if (ret == SOCKET_ERROR)
    {
#if defined(__LINUX__)
        if (errno == EWOULDBLOCK)
        {
            return SOCKET_ERROR_WOULDBLOCK;
        }
#elif defined(__WINDOWS__)
        int wsaError = WSAGetLastError();
        if (wsaError == WSAEWOULDBLOCK)
        {
            return SOCKET_ERROR_WOULDBLOCK;
        }
#endif
    }
    return ret;
}